//  创建切片
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// 引入store包(localStorage 第三方包)
import store from 'store';
// console.log('store', store.get('userinfo'));

// 定义初始的数据类型
interface stateType {
    adminname: string,
    checkedkeys: Array<any>,
    role: number,
    token: string
}

// 定义初始的数据
// 该处的仓库中的数据是从本地获取数据,这样也能实现仓库的持久化
const initialState: stateType = {
    adminname: store.get('userinfo') ? store.get('userinfo').adminname : '',
    checkedkeys: store.get('userinfo') ? store.get('userinfo').checkedkeys : [],
    role: store.get('userinfo') ? store.get('userinfo').role : 0,
    token: store.get('userinfo') ? store.get('userinfo').token : ''
}

// 定义shop购物车切片
export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        // 修改adminname 
        setAdminname(state, actions: PayloadAction<string>) {
            state.adminname = actions.payload
        },
        // 修改checkedkeys 
        setCheckedkeys(state, actions: PayloadAction<Array<any>>) {
            state.checkedkeys = actions.payload
        },
        // 修改role
        setRole(state, actions: PayloadAction<number>) {
            state.role = actions.payload
        },
        // 修改token
        setToken(state, actions: PayloadAction<string>) {
            state.token = actions.payload
        }

    }
})

//页面中使用该方法实现操作修改rtk仓库中的count数据
export const {
    setAdminname,
    setCheckedkeys,
    setRole,
    setToken
} = userSlice.actions;

// 导出reducer
export default userSlice.reducer

